<template>
  <div style="height: 100vh;display: flex; align-items: center; justify-content: center; background-color: #E6A23C">
    <div style="display: flex;background-color: white; width: 90%; border-radius: 10px; overflow: hidden">
      <div style="flex: 1">
        <img :src="imgSrc" alt="Logo" style="width: 100%">
      </div>
<!--      上下垂直居中，左右水平居中-->
      <div style="flex: 1;display: flex;align-items: center; justify-content: center">
        <el-form :rules="rules" :model="user" style="width: 50%" ref="registerRef">
          <div style="font-size: 30px;font-weight: bold; text-align: center;margin-bottom: 20px">注册三谷工具库账号</div>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号" v-model="user.username"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请输入密码" v-model="user.password" show-password></el-input>
          </el-form-item>

          <el-form-item prop="password2">
            <el-input prefix-icon="el-icon-lock" size="medium" placeholder="请确认密码" v-model="user.password2" show-password></el-input>
          </el-form-item>

<!--          <el-form-item prop="code">-->
<!--            <div style="display: flex">-->
<!--              <el-input prefix-icon="el-icon-circle-check" size="medium" placeholder="输入图片验证码" style="flex: 1" v-model="user.code"></el-input>-->
<!--              <div style="flex: 1;height: 36px">-->
<!--                <valid-code @update:value="getCode"/>-->
<!--              </div>-->
<!--            </div>-->
<!--          </el-form-item>-->

<!--          <div style="height: 40px;margin-bottom: 20px;" id="box2"></div>-->

          <el-form-item prop="phone">
            <div style="display: flex; align-items: center">
              <el-input prefix-icon="el-icon-phone-outline" size="medium" placeholder="绑定手机号" style="flex: 1" v-model="user.phone"></el-input>
              <div style="margin-left: 10px" >
                <el-button @click="readySmsSend" :disabled="isSendingSmsCode">{{smsCode}}</el-button>
              </div>
            </div>
          </el-form-item>

          <el-form-item prop="smsCode">
            <div style="display: flex">
              <el-input prefix-icon="el-icon-circle-check" size="medium" placeholder="输入短信验证码" style="flex: 1" v-model="user.smsCode"></el-input>
            </div>
          </el-form-item>

          <el-form-item prop="role">
            <el-radio-group v-model="user.role">
              <el-radio label="用户"></el-radio>
              <el-radio label="管理员"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button type="warning" style="width: 100%" @click="register">
              注册
            </el-button>
          </el-form-item>

          <div style="display: flex">
            <div style="flex: 1">已经有账号？请点击<span style="color: #1890ff; cursor: pointer" @click="$router.push('/login')">登录</span>
            </div>
            <div style="flex: 1;text-align: right">
              <img v-if="showMiniProgram" style="position: absolute; width: 140px; height: 140px;" src="../assets/qrImg.jpg" alt="管理员微信二维码" @click="isShowAdminQr">
              <span style="color: #ff184e; cursor: pointer" @click="isShowAdminQr">注册不了联系管理员</span>
            </div>
          </div>
        </el-form>

        <el-dialog :visible.sync="dialogVisible" width="30%">
          <div style="height: 40px;margin-bottom: 20px;" id="box2"></div>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<!--<script src="https://68api.com/static/captcha/captcha.min.js"></script>-->
<script>
import ValidCode from "@/components/ValidCode";
import logoImg from "@/assets/sangulogo.png";
import QrImg from "@/assets/qrImg.jpg";
export default {
  name: "Register",
  components: {
    ValidCode
  },
  // comments: {
  //   ValidCode
  // },
  data(){
    //用户名校验
    const validateName = (rule,value,callback) => {
      if (value === ''){
        callback(new Error('请填入用户名'));
      }else {
        callback();
      }
    }
    //密码校验
    const validatePassword = (rule,pwd,callback) => {
      if (pwd === ''){
        callback(new Error('请填入密码'));
      } else {
        callback();
      }
    }
    //两次密码校验
    const checkPassword = (rule,pwd,callback) => {
      if (pwd === ''){
        callback(new Error('请填入确认密码'));
      } else if (pwd !== this.user.password){
        callback(new Error('请确认密码是否一致'))
      } else {
        callback();
      }
    }
    //验证码校验
    const validateCode = (rule,value,callback) => {
      if (value === ''){
        callback(new Error('请输入验证码'));
      } else if (value.toLowerCase() !== this.code){
        callback(new Error('验证码错误'))
      } else {
        callback();
      }
    }
    //手机号校验
    const validatePhone = (rule,value,callback) => {
      const regular = /^1[3-9]\d{9}$/;
      if (value === ''){
        callback(new Error('请输入手机号'));
      } else if (!regular.test(value)){
        callback(new Error('手机号格式不正确'))
      } else {
        callback();
      }
    }
    //短信验证码校验
    const validateSmsCode = (rule,value,callback) => {
      if (value === ''){
        callback(new Error('短信验证码不能空'));
      } else {
        callback();
      }
    }
    return {
      dialogVisible: false,
      imgSrc: logoImg,
      showMiniProgram: false,
      captchaObj: null,
      appId: 6813,
      urlStart: null,
      urlVerify: null,
      smsCode: '获取短信验证码',
      count: 60,
      isSendingSmsCode: false, //是否正在发送短信验证码
      code: '', //验证码组件传递来的变量
      user: {
        username: '',
        password: '',
        password2: '',
        code: '', //表单里用户输入的
        phone: '',
        role: '用户',
        smsCode: '',
        apiToken: ''
      },
      rules: {
        // username: [
        //   { require: true,message: '请输入账号',trigger: 'blur'} //必填
        // ],
        username: [
          { trigger: 'blur', validator: validateName } //必填
        ],
        password: [
          { trigger: 'blur', validator: validatePassword }
        ],
        password2: [
          { trigger: 'blur', validator: checkPassword}
        ],
        role: [
          { require: true,message: '请选择角色',trigger: 'blur'}
        ],
        // code: [
        //   { trigger: 'blur', validator: validateCode}
        // ],
        phone: [
          { trigger: 'blur', validator: validatePhone}
        ],
        smsCode: [
          { trigger: 'blur', validator: validateSmsCode}
        ]
      }
    }
  },
  created() {

  },
  mounted() {
    //引入三方组件库 //改为弹窗时再调用
    // this.import68Api();
    //这个钩子函数会在组件挂载到DOM后执行，确保此时DOM元素已经存在
    // this.initCaptcha();
  },
  beforeDestroy(){
    //清除倒计时
    // if (this.smsCodeTimer){
    //   clearInterval(this.smsCodeTimer);
    // }
  },
  computed:{
    //获取LOGO图片
    // getImgSrc(){
    //   return this.showMiniProgram ? './assets/userhead.jpg' : './assets/sangulogo.png';
    // },
  },
  methods:{
    //管理员二维码是否显示
    isShowAdminQr(){
      this.showMiniProgram = !this.showMiniProgram;
      // this.showMiniProgram ? this.imgSrc=QrImg : this.imgSrc=logoImg;
    },
    //引入三方组件库
    import68Api(){
      const scriptElement = document.createElement('script');
      scriptElement.type = 'text/javascript';
      scriptElement.src = 'https://68api.com/static/captcha/captcha.min.js'
      scriptElement.onload = () => this.initCaptcha();
      document.body.appendChild(scriptElement);
    },
    //初始化拖动验证码
    initCaptcha(){
      const box = document.getElementById('box2');
      if (!box){
        this.$message.error("拖动验证组件不存在");
        return;
      }
      this.captchaObj = captcha68Api.init(box,(token) => {
        console.log("token："+token);
        this.user.apiToken = token;
        this.dialogVisible = false; //拖拽成功后关闭弹窗，正式发送
        this.sendSmsCode();
      },{
        appId: this.appId,
        cutShow: false
      })
    },
    //刷新拖动验证码：用在后端发生异常时，回调刷新
    refreshCaptcha(){
      if (this.captchaObj){
        this.captchaObj.refresh();
      }
    },
    startSmsCodeTimer(){
      let countDown = setInterval(() => {
        if (this.count < 1){
          this.isSendingSmsCode = false;
          this.smsCode = '获取验证码';
          this.count = 60;
          clearInterval(countDown);
        }else {
          this.isSendingSmsCode = true;
          this.smsCode = this.count-- + '秒后重试'
        }
      },1000)
    },
    readySmsSend(){
      if (this.isSendingSmsCode) return;

      //手机号或图形验证码不能出错
      // if (!this.user.phone || !this.user.code){
      //   this.$message.error('请填写手机号和图形验证码');
      //   return;
      // }

      //获取短信验证码时只需要拼图和手机号即可，无需全表单校验。
      if (!this.user.phone){
        this.$message.error('请填写手机号');
        return;
      }

      this.dialogVisible = true;
      //准备调用
      this.import68Api()

      //临时开一下通道
      // this.user.apiToken = '103FB872BD6E96E9';

      //拖动验证码校验
      // if (!this.user.apiToken){
      //   this.$message.error("请先托动图形验证码")
      //   return;
      // }
    },
    sendSmsCode(){
      this.$request.post('/login/getSmsCode',this.user).then(res => {
        if (res.code === '200'){
          this.$message.success(res.data)
          this.startSmsCodeTimer(); //按钮开始倒计时
        }else {
          this.$message.error(res.msg)
          this.refreshCaptcha(); //刷新拖动验证码，重试
        }
      })
    },
    getCode(code){
      console.log(code);
      // this.code=code; //即使对象里没有声明code，使用时会自动定义code
      this.code= code.toLowerCase()
    },
    register(){
      this.$refs['registerRef'].validate((valid) => {
        if (valid) {
          //验证通过
          console.log(this.code);
          this.$request.post('/login/register',this.user).then(res => {
            // console.log(res);
            if (res.code === '200'){
              this.$message.success('注册成功')
              this.$router.push('/login')
            }else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>